package com.pingan.generator.api.util;

import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringHelper implements ApplicationContextAware {
	 /**
     * 日志对象
     */
    protected Logger logger = LoggerFactory.getLogger(getClass());

	// 当前的Spring上下文
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext arg0) throws BeansException {
		applicationContext = arg0;
	}

	/**
	 * @param beanName
	 *            bean Id
	 * @return 如果获取失败，则返回Null
	 * 功能：通过BeanId获取Spring管理的对象
	 */
	public Object getObject(String beanName) {
		Object object = null;
		try {
			object = applicationContext.getBean(beanName);
		} catch (Exception e) {
			logger.error("",e);
		}
		return object;
	}

	/**
	 * @return
	 *         功能：获取Spring的ApplicationContext
	 */
	public ApplicationContext getContext() {
		return applicationContext;
	}

	/**
	 * @param clazz
	 *            要获取的Bean类
	 * @return 如果获取失败，则返回Null
	 */
	public <T> T getObject(Class<T> clazz) {
		try {
			return applicationContext.getBean(clazz);
		} catch (Exception e) {
			logger.error("",e);
		}
		return null;
	}

	/**
	 * @param code
	 *            配置文件中消息提示的代码
	 * @param locale
	 *            当前的语言环境
	 * @return 当前语言对应的消息内容
	 * 功能：获取当前语言对应的消息内容
	 */
	public String getMessage(String code, Locale locale) {
		String message;
		try {
			message = applicationContext.getMessage(code, null, locale);
		} catch (Exception e) {
			logger.error("",e);
			message = "";
		}
		return message;
	}

	

	
}
